<template>
  <!---搜索表单-->
  <div class="search-div">
    <el-form label-width="70px" size="small">
      <el-row>
        <el-col :span="12">
          <el-form-item label="关键字">
            <el-input v-model="recordPatientDto.username" style="width: 100%" placeholder="姓名"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row style="display:flex">
        <el-button type="primary" size="small" @click="fetchData">搜索</el-button>
        <el-button size="small" @click="resetData">重置</el-button>
      </el-row>
    </el-form>
    <div class="tools-div">
      <el-button type="success" size="small" @click="addShow">添 加 档 案</el-button>
    </div>
  </div>

  <!---数据表格-->
  <el-table :data="list" style="width: 100%">
    <el-table-column type="index" label="序号" width="100"></el-table-column>
    <el-table-column prop="name" label="姓名" />
    <el-table-column prop="sex" label="性别" #default="scope">{{ scope.row.sex == 0 ? '男' : '女' }}</el-table-column>
    <el-table-column prop="phone" label="手机号" />
    <el-table-column prop="rename" label="民族" />
    <el-table-column prop="bmi" label="BMI" />
    <el-table-column prop="birthday" label="出生日期" />
    <el-table-column prop="address" label="现居地址" />
    <el-table-column prop="residentsType" label="人群标签" />
    <el-table-column label="操作" align="center" width="280" #default="scope">
      <el-button type="success" size="small" @click="detailShow(scope.row)">详情</el-button>
      <el-button type="danger" size="small" @click="deleteById(scope.row)">删除</el-button>
    </el-table-column>
  </el-table>
  <el-dialog v-model="dialogVisible" :title="详情" width="85%">
    <el-form label-width="120px">
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="健康档案" name="first">
          <el-descriptions title="基本信息" column="4">
            <el-descriptions-item label="姓名">{{recordPatient.name}}</el-descriptions-item>
            <el-descriptions-item label="性别">{{recordPatient.sex== 0 ? '男' : '女'}}</el-descriptions-item>
            <el-descriptions-item label="手机号">{{recordPatient.phone}}</el-descriptions-item>
            <el-descriptions-item label="身份证号">{{recordPatient.idNumber}}</el-descriptions-item>
            <el-descriptions-item label="文化程度">{{recordPatient.edname}}</el-descriptions-item>
            <el-descriptions-item label="婚姻状况">{{recordPatient.msname}}</el-descriptions-item>
            <el-descriptions-item label="民族">{{recordPatient.rename}}</el-descriptions-item>
            <el-descriptions-item label="紧急联系人">{{recordPatient.emergencyContact}}</el-descriptions-item>
            <el-descriptions-item label="联系人电话">{{recordPatient.contactNumber}}</el-descriptions-item>
            <el-descriptions-item label="出生日期">{{recordPatient.birthday}}</el-descriptions-item>
            <el-descriptions-item label="职业">{{recordPatient.roname}}</el-descriptions-item>
            <el-descriptions-item label="现居地址">{{recordPatient.address}}</el-descriptions-item>
            <el-descriptions-item label="户籍地址">{{recordPatient.prAddress}}</el-descriptions-item>
            <el-descriptions-item label="付费类型">{{recordPatient.exname}}</el-descriptions-item>
            <!-- <el-descriptions-item label="病人标签">
              <el-tag size="warning" v-for="item in biaoqian.split(',')">{{item}}</el-tag>
            </el-descriptions-item> -->
          </el-descriptions>
          <el-descriptions title="基本信息" column="4">
            <el-descriptions-item label="身高">{{recordPatient.height}}</el-descriptions-item>
            <el-descriptions-item label="体重 ">{{recordPatient.weight}}</el-descriptions-item>
            <el-descriptions-item label="BMI">{{recordPatient.bmi}}</el-descriptions-item>
            <el-descriptions-item label="血型">{{recordPatient.rbname}}</el-descriptions-item>
            <el-descriptions-item label="RH阴性">{{recordPatient.rhNegative}}</el-descriptions-item>
            <el-descriptions-item label="过敏史">{{recordPatient.allergic}}</el-descriptions-item>
            <el-descriptions-item label="既往史">{{recordPatient.previous}}</el-descriptions-item>
            <el-descriptions-item label="就诊史">{{recordPatient.medical}}</el-descriptions-item>
            <el-descriptions-item label="家族病史">{{recordPatient.family}}</el-descriptions-item>
          </el-descriptions>
        </el-tab-pane>
        <el-tab-pane label="患者干预" name="second">暂无患者干预记录</el-tab-pane>
        <el-tab-pane label="评估记录" name="fourth">
          <el-timeline-item v-for="(items,index) in lists" placement="top" @click="editShows(items)">
            <el-card>
              <h4>{{items.name}}</h4>
              <p>{{ items.shifou }}</p>
              <p v-if="items.dengji=='无'">{{ items.weilai }}</p>
              <p v-if="items.weilai=='无'">{{ items.dengji }}</p>
              <p>{{items.createTime}}</p>
            </el-card>
          </el-timeline-item>
        </el-tab-pane>
        <el-tab-pane label="设备信息" name="fifth">暂无已绑定设备信息</el-tab-pane>
        <el-tab-pane label="健康信息" name="sixth">暂无健康信息</el-tab-pane>
      </el-tabs>
      <el-form-item>
        <el-button type="primary" size="small" @click="editShow(recordPatient.id)">编辑档案信息</el-button>
        <el-button @click="dialogVisible = false">返回</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
  <el-dialog v-model="dialogPopups" title="添加或修改" width="75%">
    <el-descriptions title="健康信息" column="4">
      <el-descriptions-item label="姓名">
        <el-input style="width: 180px" size="mini" v-model="recordDto.name"></el-input>
      </el-descriptions-item>
      <el-descriptions-item label="身份证号">
        <el-input style="width: 180px" size="mini" v-model="recordDto.idNumber"></el-input>
      </el-descriptions-item>
      <el-descriptions-item label="联系电话">
        <el-input style="width: 180px" size="mini" v-model="recordDto.phone"></el-input>
      </el-descriptions-item>
      <el-descriptions-item label="性别">
        <el-select v-model="recordDto.sex" placeholder="请选择">
          <el-option
            v-for="item in sex"
            :key="item.value"
            :label="item.label"
            :value="item.value"
            @change="ceshi"
          >{{item.label}}</el-option>
        </el-select>
      </el-descriptions-item>
      <el-descriptions-item label="出生日期">
        <el-date-picker v-model="recordDto.birthday" type="date" placeholder="选择出生日期"></el-date-picker>
      </el-descriptions-item>
      <el-descriptions-item label="民族">
        <el-select v-model="recordDto.reId" placeholder="请选择">
          <el-option v-for="item in ethnic" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-descriptions-item>
      <el-descriptions-item label="婚姻状况">
        <el-select v-model="recordDto.msId" placeholder="请选择">
          <el-option
            v-for="item in maritalstatus"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-descriptions-item>
      <el-descriptions-item label="职业">
        <el-select v-model="recordDto.roId" placeholder="请选择">
          <el-option v-for="item in occupation" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-descriptions-item>
      <el-descriptions-item label="文化程度">
        <el-select v-model="recordDto.edId" placeholder="请选择">
          <el-option v-for="item in education" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-descriptions-item>
      <el-descriptions-item label="紧急联系人">
        <el-input style="width: 180px" size="mini" v-model="recordDto.emergencyContact"></el-input>
      </el-descriptions-item>
      <el-descriptions-item label="联系电话">
        <el-input style="width: 180px" size="mini" v-model="recordDto.contactNumber"></el-input>
      </el-descriptions-item>
      <el-descriptions-item label="费用类型">
        <el-radio-group v-model="recordDto.exId" class="ml-4">
          <el-radio
            size="large"
            v-for="item in expensetype"
            :key="item.id"
            :label="item.id"
            :value="item.id"
            :disabled="item.disabled"
          >{{ item.name }}</el-radio>
        </el-radio-group>
      </el-descriptions-item>
    </el-descriptions>
    <el-divider />
    <el-descriptions title="常住地址" column="3">
      <el-descriptions-item label>
        <el-select v-model="recordDto.selectedProvince" @change="provinceChanged">
          <el-option disabled value>请选择省份</el-option>
          <el-option
            v-for="province in provinces"
            :label="province.name"
            :value="province.id"
          >{{province.name}}</el-option>
        </el-select>
      </el-descriptions-item>
      <el-descriptions-item>
        <el-select v-model="recordDto.selectedCity" @change="cityChanged">
          <el-option disabled value>请选择城市</el-option>
          <el-option v-for="city in cities" :label="city.name" :value="city.id">{{city.name}}</el-option>
        </el-select>
      </el-descriptions-item>
      <el-descriptions-item>
        <el-select v-model="recordDto.selectedDistrict" @change="districtChanged">
          <el-option disabled value>请选择区/县</el-option>
          <el-option
            v-for="district in districts"
            :label="district.name"
            :value="district.id"
          >{{district.name}}</el-option>
        </el-select>
      </el-descriptions-item>
      <el-descriptions-item label="详细地址">
        <el-input style="width: 180px" size="mini" v-model="recordDto.address"></el-input>
      </el-descriptions-item>
    </el-descriptions>
    <el-divider />
    <!-- ======================================================== -->
    <el-descriptions title="户籍地址" column="3">
      <el-descriptions-item label>
        <el-select v-model="recordDto.prselectedProvince" @change="prprovinceChanged">
          <el-option disabled value>请选择省份</el-option>
          <el-option
            v-for="province in prprovinces"
            :label="province.name"
            :value="province.id"
          >{{province.name}}</el-option>
        </el-select>
      </el-descriptions-item>
      <el-descriptions-item>
        <el-select v-model="recordDto.prselectedCity" @change="prcityChanged">
          <el-option disabled value>请选择城市</el-option>
          <el-option v-for="city in prcities" :label="city.name" :value="city.id">{{city.name}}</el-option>
        </el-select>
      </el-descriptions-item>
      <el-descriptions-item>
        <el-select v-model="recordDto.prselectedDistrict" @change="prdistrictChanged">
          <el-option disabled value>请选择区/县</el-option>
          <el-option
            v-for="district in prdistricts"
            :label="district.name"
            :value="district.id"
          >{{district.name}}</el-option>
        </el-select>
      </el-descriptions-item>
      <el-descriptions-item label="详细地址">
        <el-input style="width: 180px" size="mini" v-model="recordDto.prAddress"></el-input>
      </el-descriptions-item>
    </el-descriptions>
    <el-divider />
    <el-descriptions title="健康信息" column="4">
      <el-descriptions-item label="身高">
        <el-input style="width: 180px" size="mini" v-model="recordDto.height" />cm
      </el-descriptions-item>
      <el-descriptions-item label="体重">
        <el-input style="width: 180px" size="mini" v-model="recordDto.weight" />kg
      </el-descriptions-item>
      <el-descriptions-item label="血型">
        <el-select v-model="recordDto.rbId" placeholder="请选择">
          <el-option v-for="item in blood" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-descriptions-item>
      <el-descriptions-item label="RH阴性">
        <el-select v-model="recordDto.rhNegative" placeholder="请选择">
          <el-option
            v-for="item in rhNegative"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-descriptions-item>
    </el-descriptions>
    <el-descriptions column="1">
  <el-descriptions-item label="过敏史">
    <el-radio v-model="allergic" :label="false">无</el-radio>
    <el-radio v-model="allergic" :label="true">有</el-radio>
    <el-input v-if="allergic" v-model="recordDto.allergic" placeholder="请输入过敏史" style="width: 580px" size="mini"></el-input>
  </el-descriptions-item>
</el-descriptions>
<el-descriptions column="1">
  <el-descriptions-item label="既往史">
    <el-radio v-model="previous" :label="false">无</el-radio>
    <el-radio v-model="previous" :label="true">有</el-radio>
    <el-input v-if="previous" v-model="recordDto.previous" placeholder="请输入既往史" style="width: 580px" size="mini"></el-input>
  </el-descriptions-item>
</el-descriptions>
<el-descriptions column="1">
  <el-descriptions-item label="就诊史">
    <el-radio v-model="medical" :label="false">无</el-radio>
    <el-radio v-model="medical" :label="true">有</el-radio>
    <el-input v-if="medical" v-model="recordDto.medical" placeholder="请输入具体过敏史" style="width: 580px" size="mini"></el-input>
  </el-descriptions-item>
</el-descriptions>
<el-descriptions column="1">
  <el-descriptions-item label="家庭史">
    <el-radio v-model="family" :label="false">无</el-radio>
    <el-radio v-model="family" :label="true">有</el-radio>
    <el-input v-if="family" v-model="recordDto.family" placeholder="请输入具体过敏史" style="width: 580px" size="mini"></el-input>
  </el-descriptions-item>
    </el-descriptions>
    <el-divider />
    <!-- <el-descriptions title="病情档案" column="4">
  <el-descriptions-item label="居民类型">
      <el-radio v-model="recordDto.residentsType" label="一般人群">一般人群</el-radio>
      <el-radio v-model="recordDto.residentsType" label="慢病患者">慢病患者</el-radio>
  
      如果选择慢病患者，展示多选框和其他内容 
      
      <div v-if="recordDto.residentsType === '慢病患者'">
        <b>专案信息</b>
        <el-checkbox-group v-model="recordDto.label">
          <el-checkbox v-for="disease in label" :key="disease.id" :label="disease.id"  @change="handleCheckboxChange">{{ disease.name }}</el-checkbox>
        </el-checkbox-group>
        <el-descriptions title="高血压" column="4" v-if="recordDto.label.includes(1)">
          <el-descriptions-item label="诊断名称">
            <el-select v-model="recordDto.hypertensionDto.diagnosisNameId" placeholder="请选择">
              <el-option
                v-for="item in hypertensionDiagnosisName"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-descriptions-item>
          <el-descriptions-item label="诊断编码">
            <el-input style="width: 180px" size="mini" v-model="recordDto.hypertensionDto.diagnosisCode"></el-input>
          </el-descriptions-item>
          <el-descriptions-item label="收缩压(mmhg)">
            <el-input style="width: 180px" size="mini" v-model="recordDto.hypertensionDto.systolicPressure"></el-input>
          </el-descriptions-item>
          <el-descriptions-item label="高血压类型">
            <el-select v-model="recordDto.hypertensionDto.hypertensionTypeId" placeholder="请选择">
              <el-option
                v-for="item in hypertensionType"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-descriptions-item>
          <el-descriptions-item label="确诊日期">
              <el-date-picker v-model="recordDto.hypertensionDto.diagnosisDate" type="date" placeholder="选择确诊日期"></el-date-picker>
          </el-descriptions-item>
          <el-descriptions-item label="确诊医生">
            <el-input style="width: 180px" size="mini" v-model="recordDto.hypertensionDto.diagnosingDoctor"></el-input>
          </el-descriptions-item>
        </el-descriptions>
        <el-descriptions title="糖尿病" column="4" v-if="recordDto.label.includes(2)">
          <el-descriptions-item label="诊断名称">
            <el-select v-model="recordDto.diabetesDto.diagnosisNameId" placeholder="请选择">
              <el-option
                v-for="item in diabetesDiagnosisName"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-descriptions-item>
          <el-descriptions-item label="诊断编码">
            <el-input style="width: 180px" size="mini" v-model="recordDto.diabetesDto.diagnosisCode"></el-input>
          </el-descriptions-item>
          <el-descriptions-item label="餐后2h">
            <el-input style="width: 180px" size="mini" v-model="recordDto.diabetesDto.postprandial2hGlucose"></el-input>
          </el-descriptions-item>
          <el-descriptions-item label="糖尿病类型">
            <el-select v-model="recordDto.diabetesDto.diabetesTypeId" placeholder="请选择">
              <el-option
                v-for="item in diabetesType"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-descriptions-item>
          <el-descriptions-item label="确诊日期">
              <el-date-picker v-model="recordDto.diabetesDto.diagnosisDate" type="date" placeholder="选择确诊日期"></el-date-picker>
          </el-descriptions-item>
          <el-descriptions-item label="确诊医生">
            <el-input style="width: 180px" size="mini" v-model="recordDto.diabetesDto.diagnosingDoctor"></el-input>
          </el-descriptions-item>
        </el-descriptions>
        <el-descriptions title="冠心病" column="4" v-if="recordDto.label.includes(3)">
          <el-descriptions-item label="诊断名称">
            <el-select v-model="recordDto.coronaryDto.coronaryNameId" placeholder="请选择">
              <el-option
                v-for="item in coronaryName"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-descriptions-item>
          <el-descriptions-item label="诊断编码">
            <el-input style="width: 180px" size="mini" v-model="recordDto.coronaryDto.diagnosisCode"></el-input>
          </el-descriptions-item>
          <el-descriptions-item label="冠心病类型">
            <el-select v-model="recordDto.coronaryDto.coronaryTypeId" placeholder="请选择">
              <el-option
                v-for="item in coronaryType"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-descriptions-item>
          <el-descriptions-item label="确诊日期">
              <el-date-picker v-model="recordDto.coronaryDto.diagnosisDate" type="date" placeholder="选择确诊日期"></el-date-picker>
          </el-descriptions-item>
          <el-descriptions-item label="确诊医生">
            <el-input style="width: 180px" size="mini" v-model="recordDto.coronaryDto.diagnosingDoctor"></el-input>
          </el-descriptions-item>
        </el-descriptions>
    </div>
    </el-descriptions-item>-->
    <!-- </el-descriptions> -->

    <!-- <el-descriptions column="3">
  <el-descriptions-item label="管理医生">
    <el-select v-model="recordDto.guanliyisheng" placeholder="请选择">
      <el-option v-for="item in guanliyisheng" :key="item.value" :label="item.label" :value="item.label"></el-option>
    </el-select>
  </el-descriptions-item>
  <el-descriptions-item label="健康管理师">
    <el-select v-model="recordDto.jiankangguanlishi" placeholder="请选择">
      <el-option v-for="item in jiankangguanlishi" :key="item.value" :label="item.label" :value="item.label"></el-option>
    </el-select>
  </el-descriptions-item>
  <el-descriptions-item label="专科医生">
    <el-select v-model="recordDto.zhuankeyisheng" placeholder="请选择">
      <el-option v-for="item in zhuankeyisheng" :key="item.value" :label="item.label" :value="item.label"></el-option>
    </el-select>
  </el-descriptions-item>
    </el-descriptions>-->
    <el-form-item>
      <el-button type="primary" @click="submit">提交</el-button>
      <el-button @click="dialogPopups = false">取消</el-button>
    </el-form-item>
  </el-dialog>

  <el-dialog v-model="dialogVisiblesa" title="高血压评估结果" width="70%">
                        <el-form-item label="是否抽烟">
                            <el-radio-group v-model="pingg.yan">
                                <el-radio :label="2">是</el-radio>
                                <el-radio :label="1">否</el-radio>
                            </el-radio-group>
                        </el-form-item>

                        <el-form-item label="运动频率">
                            <el-radio-group v-model="pingg.yun">
                                <el-radio :label="1">经常</el-radio>
                                <el-radio :label="2">不运动</el-radio>
                            </el-radio-group>
                        </el-form-item>

                        <el-form-item label="饮食习惯">
                            <el-radio-group v-model="pingg.yin">
                                <el-radio :label="2">偏高盐</el-radio>
                                <el-radio :label="1">健康饮食</el-radio>
                            </el-radio-group>
                        </el-form-item>

                        <el-form-item label="家族中是否有高血压、心血管疾病等相关疾病的患者？">
                            <el-radio-group v-model="pingg.yichaun">
                                <el-radio :label="2">是</el-radio>
                                <el-radio :label="1">否</el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item label="收缩压">
                            <el-text/>{{ pingg.shousuo }}
                        </el-form-item>
                        <el-form-item label="舒张压">
                            <el-text/>{{ pingg.shuzhang }}
                        </el-form-item>

                        <el-form-item label="是否患有高血压">
                            <el-text/>{{ pingg.shifou }}
                        </el-form-item>

                        <el-form-item label="患有高血压的等级:" v-if="pingg.weilai=='无'">
                            <el-text/>{{ pingg.dengji }}
                        </el-form-item>

                        <el-form-item label="未患有高血压，会患有高血压的等级:" v-if="pingg.dengji=='无'">
                            <el-text/>{{ pingg.weilai }}
                        </el-form-item>
                </el-dialog> 



  <el-pagination
    v-model:current-page="pageParams.page"
    v-model:page-size="pageParams.limit"
    :page-sizes="[3, 10, 15, 20]"
    @size-change="fetchData"
    @current-change="fetchData"
    layout="total, sizes, prev, pager, next"
    :total="total"
  />
</template>

<script setup>

import { ref, onMounted,onUnmounted } from 'vue'
import {
  findRecord,
  findRecordPatient,
  saveRecordPatient,
} from '@/api/recordpatient'
import { findEthnicAll } from '@/api/recordethnic'
import { findMaritalstatusAll } from '@/api/recordmaritalstatus'
import { findOccupationAll } from '@/api/recordoccupation'
import { findEducationAll } from '@/api/recordeducation'
import { findDistrict } from '@/api/district'
import { findExpensetype } from '@/api/recordexpensetype'
import { findRecordBlood } from '@/api/recordblood'
import { v4 as uuidv4 } from 'uuid';
import { findJiluById,findJiluByUserId } from '@/api/jilu';
import {describeFaceVerifyAutoRoute} from '@/api/describeFaceVerifyAutoRoute'
import {initFaceVerifyAutoRoute} from '@/api/initFaceVerifyAutoRoute'
import axios from 'axios';
// import { findLabelAll } from '@/api/recordlabel'
// import { findRecordDiagnosisNameAll } from '@/api/recorddiagnosisName'
// import { findRecordDiabetesNameAll } from '@/api/recorddiabetes'
// import { findRecordHypertensionTypeAll } from '@/api/recordhypertensionType'
// import { findRecordCoronaryNameAll } from '@/api/recordcoronaryName'
// import { findRecordCoronaryTypeAll } from '@/api/recordcoronaryType'
// import { findRecordDiabetesTypeAll } from '@/api/recorddiabetesType'
import { ElMessage, ElMessageBox } from 'element-plus'

const lists = ref([])

const pingg = ref({
  name:'高血压评估',
  yan:'',
  yun:'',
  yin:'',
  yichaun:'',
  shuzhang:'',
  shousuo:'',
  shifou:'',
  dengji:'',
  weilai:''
})

const findJiluAll = async(id)=>{
    const {data} = await findJiluByUserId(id)
    lists.value = data
}

const dialogVisiblesa = ref(false)

const editShows = async(items)=>{
    dialogVisiblesa.value = true
    const {data} = await findJiluById(items.id)
    pingg.value = data
}
//数据模板
let list = ref([])

//标签
let biaoqian = ref()

const ress = ref('')

//详情数据模版
let recordPatient = ref()
//分页总条数
let total = ref(0)

// //高血压诊断名称
// const hypertensionDiagnosisName = ref([])

// //高血压类型
// const hypertensionType = ref([])

// //糖尿病诊断名称
// const diabetesDiagnosisName = ref([])

// //糖尿病类型
// const diabetesType = ref([])

// //冠心病诊断名称
// const coronaryName = ref([])

// //冠性病类型
// const coronaryType = ref([])

// //脑卒中诊断名称
// const strokeName = ref([])

// //脑卒中类型
// const strokeType = ref([])

// //慢阻肺诊断名称
// const chronicName = ref([])
//弹窗
const dialogVisible = ref(false)
const dialogPopups = ref(false)
const pageParamsForm = {
  page: 1,
  limit: 3,
}
//民族下拉框
const ethnic = ref([])

//过敏史
const allergic = ref(false)
//既往史
const previous = ref(false)
//就诊史
const medical = ref(false)
//家庭史
const family = ref(false)

//婚姻状况下拉框
const maritalstatus = ref([])

//性别下拉框
const sex = ref([
  {
    value: '0',
    label: '男',
  },
  {
    value: '1',
    label: '女',
  },
])

// //管理医生
// const guanliyisheng = ref([
//   {
//     value: '0',
//     label: '张萌萌',
//   },
//   {
//     value: '1',
//     label: '刘德华',
//   },
// ])

// //健康管理师
// const jiankangguanlishi = ref([
//   {
//     value: '0',
//     label: '刘亦菲',
//   },
//   {
//     value: '1',
//     label: '赵露思',
//   },
// ])

// //专科医生
// const zhuankeyisheng = ref([
//   {
//     value: '0',
//     label: '张萌萌',
//   },
//   {
//     value: '1',
//     label: '王海丽',
//   },
// ])
//RH阴性
const rhNegative = ref([
  {
    value: '是',
    label: '是',
  },
  {
    value: '否',
    label: '否',
  },
  {
    value: '不详',
    label: '不详',
  },
])
//费用类型单选框
const expensetype = ref([])

// //存储各个疾病的布局内容
// const diseaseInputs = ref({})

//现居地址三级联动
const provinces = ref([]) // 省份数据
const cities = ref([]) // 城市数据
const districts = ref([]) // 区/县数

//户籍地址三级联动
const prprovinces = ref([]) // 省份数据
const prcities = ref([]) // 城市数据
const prdistricts = ref([]) // 区/县数

//定义三级联动省市县的信息
const selectedProvincetem = ref()
const selectedCitytem = ref()
const selectedDistricttem = ref()

//定义三级联动省市县的信息
const prselectedProvincetem = ref()
const prselectedCitytem = ref()
const prselectedDistricttem = ref()

//职业下拉框
const occupation = ref([])

//文化程度下拉框
const education = ref([])

//血型下拉框
const blood = ref([])

// //病标签复选框
// const label = ref([])

//响应tab栏
const activeName = ref('first')
const pageParams = ref(pageParamsForm)

//定义搜索表单数据模型
const recordPatientDto = ref({
  username: '',
})

//uuid
const uniqueId = uuidv4();

// 在调用实人认证服务端发起认证请求时需要传入该MetaInfo值
// var metaInfo = ref(JSON.stringify(window.getMetaInfo()));



// 定义添加表单数据模型
const recordDto = ref({
  name: '',
  sex: '',
  phone: '',
  idNumber: '',
  msId: '',
  reId: '',
  birthday: '',
  roId: '',
  edId: '',
  exId: '',
  emergencyContact: '',
  contactNumber: '',
  selectedProvince: '',
  selectedCity: '',
  selectedDistrict: '',
  address: '',
  prselectedProvince: '',
  prselectedCity: '',
  prselectedDistrict: '',
  prAddress: '',
  height: '',
  weight: '',
  rbId: '',
  rhNegative: '',
  allergic: '',
  previous: '',
  medical: '',
  family: '',
  residentsType: '一般人群',
  guanliyisheng: '',
  jiankangguanlishi: '',
  zhuankeyisheng: '',
  label: [],
  // //高血压病的Dto
  // hypertensionDto: {
  //   parentId: '', //患者id
  //   diagnosisNameId: '', //诊断名称
  //   diagnosisCode: '', //诊断编码
  //   systolicPressure: '', //收缩压
  //   hypertensionTypeId: '', //高压病类型id
  //   diagnosisDate: '', //确诊时间
  //   diagnosingDoctor: '', //确诊医生
  // },
  // //糖尿病的Dto
  // diabetesDto: {
  //   parentId: '', //患者id
  //   diagnosisNameId: '', //诊断名称
  //   diagnosisCode: '', //诊断编码
  //   postprandial2hGlucose: '', //餐后两小时
  //   diabetesTypeId: '', //糖尿病类型id
  //   diagnosisDate: '', //确诊时间
  //   diagnosingDoctor: '', //确诊医生
  // },
  // //冠心病的Dto
  // coronaryDto: {
  //   parentId: '', //患者id
  //   coronaryNameId: '', //诊断名称
  //   diagnosisCode: '', //诊断编码
  //   coronaryTypeId: '', //冠心病类型id
  //   diagnosisDate: '', //确诊时间
  //   diagnosingDoctor: '', //确诊医生
  // },
})

//姓名

//获取阿里云实人认证url参数值
const requesttt = ref({
  sceneId:'1000009897',
  outerOrderNo:uniqueId,
  productCode:'ID_PRO',
  model:'MULTI_ACTION',
  certType:"IDENTITY_CARD",
  returnUrl:'http://localhost:3001/#/recordpatient',
  // authId:'',
  // birthday:'',
  // callbackToken:'',
  // callbackUrl:'',
  // certifyId:'',
  certifyUrlStyle:'S',
  // certifyUrlType:'',
  // crop:'',
  // encryptType:'',
  // faceContrastPicture:'',
  // faceContrastPictureUrl:'',
  // faceGuardOutput:'',
  // ip:'',
  // mobile:'',
  // mode:'',
  // ossBucketName:'',
  // ossObjectName:'',
  // procedurePriority:'',
  // rarelyCharacters:'',
  // readImg:'',
  suitableType:'WEB',
  // userId:'',
  // validityDate:'',
  // voluntaryCustomizedContent:''


})
//重置按钮点击时间处理函数
const resetData = () => {
  recordDto.value = {}
}

onMounted(() => {
  fetchData()
  pollForAuthResult()// interval.value = setInterval(pollForAuthResult, 5000); // 每5秒检查一次
})

onUnmounted(() => {
  clearInterval(interval.value);
});

//分页变化
const handleSizeChange = size => {
  pageParams.value.limit = size
  fetchData()
}
const handleCurrentChange = number => {
  pageParams.value.page = number
  fetchData()
}

const fetchData = async () => {
  const { data } = await findRecord(
    pageParams.value.page,
    pageParams.value.limit,
    recordPatientDto.value
  )
  list.value = data.list
  total.value = data.total

}

//储存复选框的数组
const labelAll = ref([])

//点击添加按钮
const addShow = () => {
  findEthnic()
  findMaritalstatus()
  findOccupation()
  findEducation()
  findDistrictAll(0)
  Expensetype()
  recordBlood()
  // findLabel()
  // findRecordDiagnosisName()
  // findRecordHypertensionType()
  // findRecordDiabetesName()
  // findRecordDiabetesType()
  // findRecordCoronaryName()
  // findRecordCoronaryType()
  dialogPopups.value = true
}
//点击详情按钮
const detailShow = async row => {
  const { data } = await findRecordPatient(row.id)
  findJiluAll(row.id)
  recordPatient.value = data
  biaoqian.value = data.rlname
  dialogVisible.value = true
}

//查询所有的民族
const findEthnic = async () => {
  const { data } = await findEthnicAll()
  ethnic.value = data
}

//查询所有婚姻状况
const findMaritalstatus = async () => {
  const { data } = await findMaritalstatusAll()
  maritalstatus.value = data
}

//查询所有职业
const findOccupation = async () => {
  const { data } = await findOccupationAll()
  occupation.value = data
}

//查询文化程度
const findEducation = async () => {
  const { data } = await findEducationAll()
  education.value = data
}

//查询省地区
const findDistrictAll = async parent => {
  const { data } = await findDistrict(parent)
  provinces.value = data
  prprovinces.value = data
}

//当省下拉框内容发生改变，就查市
const provinceChanged = async () => {
  const parent = recordDto.value.selectedProvince
  console.log(parent)
  const { data } = await findDistrict(parent)
  cities.value = data

  selectedProvincetem.value = provinces.value.find(
    province => province.id === recordDto.value.selectedProvince
  )
  // 如果找到了对应的城市对象，则将其名称赋值给 recordDto.value.address
  if (selectedProvincetem.value) {
    recordDto.value.address = selectedProvincetem.value.name
  } else {
    recordDto.value.address = '' // 如果未找到对应的城市对象，则清空文本框
  }

  recordDto.value.selectedCity = ''
  recordDto.value.selectedDistrict = ''
}

//当市下拉框内容发生改变，就查县区
const cityChanged = async () => {
  const parent = recordDto.value.selectedCity
  console.log(parent)
  const { data } = await findDistrict(parent)
  districts.value = data
  selectedCitytem.value = cities.value.find(
    city => city.id === recordDto.value.selectedCity
  )
  // 如果找到了对应的城市对象，则将其名称赋值给 recordDto.value.address
  if (selectedCitytem.value) {
    recordDto.value.address =
      selectedProvincetem.value.name + selectedCitytem.value.name
  } else {
    recordDto.value.address = '' // 如果未找到对应的城市对象，则清空文本框
  }
  recordDto.value.selectedDistrict = ''
}

//当县下拉框内容发生改变，就将数据添加到recordDto.address
const districtChanged = async () => {
  selectedDistricttem.value = districts.value.find(
    district => district.id === recordDto.value.selectedDistrict
  )
  // 如果找到了对应的城市对象，则将其名称赋值给 recordDto.value.address
  if (selectedDistricttem.value) {
    recordDto.value.address =
      selectedProvincetem.value.name +
      selectedCitytem.value.name +
      selectedDistricttem.value.name
  } else {
    recordDto.value.address = '' // 如果未找到对应的城市对象，则清空文本框
  }
}

//当省下拉框内容发生改变，就查市
const prprovinceChanged = async () => {
  const parent = recordDto.value.prselectedProvince
  const { data } = await findDistrict(parent)
  prcities.value = data

  prselectedProvincetem.value = prprovinces.value.find(
    province => province.id === recordDto.value.prselectedProvince
  )
  // 如果找到了对应的城市对象，则将其名称赋值给  recordDto.value.prAddress
  if (prselectedProvincetem.value) {
    recordDto.value.prAddress = prselectedProvincetem.value.name
  } else {
    recordDto.value.prAddress = '' // 如果未找到对应的城市对象，则清空文本框
  }

  recordDto.value.prselectedCity = ''
  recordDto.value.prselectedDistrict = ''
}

//当市下拉框内容发生改变，就查县区
const prcityChanged = async () => {
  const parent = recordDto.value.prselectedCity
  const { data } = await findDistrict(parent)
  prdistricts.value = data
  prselectedCitytem.value = prcities.value.find(
    city => city.id === recordDto.value.prselectedCity
  )
  // 如果找到了对应的城市对象，则将其名称赋值给  recordDto.value.prAddress
  if (prselectedCitytem.value) {
    recordDto.value.prAddress =
      prselectedProvincetem.value.name + prselectedCitytem.value.name
  } else {
    recordDto.value.prAddress = '' // 如果未找到对应的城市对象，则清空文本框
  }
  recordDto.value.prselectedDistrict = ''
}

//当县下拉框内容发生改变，就将数据添加到 recordDto.value.prAddress
const prdistrictChanged = async () => {
  prselectedDistricttem.value = prdistricts.value.find(
    district => district.id === recordDto.value.prselectedDistrict
  )
  // 如果找到了对应的城市对象，则将其名称赋值给  recordDto.value.prAddress
  if (prselectedDistricttem.value) {
    recordDto.value.prAddress =
      prselectedProvincetem.value.name +
      prselectedCitytem.value.name +
      prselectedDistricttem.value.name
  } else {
    recordDto.value.prAddress = '' // 如果未找到对应的城市对象，则清空文本框
  }
}

//查询费用类型
const Expensetype = async () => {
  const { data } = await findExpensetype()
  expensetype.value = data
}

//查询所有血型
const recordBlood = async () => {
  const { data } = await findRecordBlood()
  blood.value = data
}
// //查询所有的病标签
// const findLabel = async () => {
//   const { data } = await findLabelAll()
//   label.value = data
// }

// //查询所有高血压诊断名称
// const findRecordDiagnosisName = async () => {
//   const { data } = await findRecordDiagnosisNameAll()
//   hypertensionDiagnosisName.value = data
// }

// //查询所有高血压类型
// const findRecordHypertensionType = async () => {
//   const { data } = await findRecordHypertensionTypeAll()
//   hypertensionType.value = data
// }

// //查询所有糖尿病诊断名称
// const findRecordDiabetesName = async () => {
//   const { data } = await findRecordDiabetesNameAll()
//   diabetesDiagnosisName.value = data
// }

// //查询所有糖尿病类型
// const findRecordDiabetesType = async () => {
//   const { data } = await findRecordDiabetesTypeAll()
//   diabetesType.value = data
// }

// //查询所有冠心病诊断名称
// const findRecordCoronaryName = async () => {
//   const { data } = await findRecordCoronaryNameAll()
//   coronaryName.value = data
// }

// //查询所有冠心病类型
// const findRecordCoronaryType = async () => {
//   const { data } = await findRecordCoronaryTypeAll()
//   coronaryType.value = data
// }
const authResult = ref(null)
const interval = ref(null)
const requestttt = ref({

});

const pollForAuthResult = async () => {
  try {
    requestttt.value.certifyId = localStorage.getItem("certifyId");
    requestttt.value.sceneId = localStorage.getItem("sceneId");
    const recordDto2 = localStorage.getItem("recordDto");
    const recordDto = JSON.parse(recordDto2)
    if (requestttt.value.certifyId != null && requestttt.value.certifyId != '' && requestttt.value.sceneId != null && requestttt.value.sceneId != '') {
      const {body} =  await describeFaceVerifyAutoRoute(requestttt.value);
    const { code, message, requestId, resultObject } = body;
    const { passed,subCode } = resultObject;
    if (subCode == 200) {
    const { code, message, data } = await saveRecordPatient(recordDto)
    if (code == 200) {
      dialogPopups.value = false
      ElMessage.success('操作成功')
      fetchData()
    }else{
      ElMessage.error("创建档案失败")
      
    }
    }else{
      ElMessage.error("认证失败")
    }
    localStorage.removeItem('certifyId');
    localStorage.removeItem('sceneId');
    localStorage.removeItem('recordDto');
    }
   
  } catch (error) {
    console.error('检查认证状态时出错', error);
  }
}

var CertifyUrl = ref('')
const startRealPersonAuth = async () => {
    try {
        const { body } = await initFaceVerifyAutoRoute(requesttt.value);
        const { code, message, resultObject } = body;
        const { certifyId, certifyUrl } = resultObject;
        if(certifyId){
          localStorage.setItem("certifyId",certifyId)
          localStorage.setItem("sceneId",requesttt.value.sceneId)
          localStorage.setItem("recordDto",JSON.stringify(recordDto.value))
        CertifyUrl.value = certifyUrl;
         // 打开认证页面
         window.location.href = CertifyUrl.value;
        }
       
    } catch (error) {
      console.error('获取实人认证URL失败', error);
}
}


      // 在 setup() 函数中引入 JavaScript 文件
      const loadScript = () => {
      return new Promise((resolve, reject) => {
        const script = document.createElement('script');
        script.src = 'https://cn-shanghai-aliyun-cloudauth.oss-cn-shanghai.aliyuncs.com/web_sdk_js/jsvm_all.js';
        script.onload = resolve;
        script.onerror = reject;
        document.head.appendChild(script);
      });
    };

      // 调用 getMetaInfo() 函数获取 MetaInfo 值
    const getMetaInfo = async () => {
      await loadScript();
      // 假设 getMetaInfo() 函数在全局作用域中可用
      const metaInfo = JSON.stringify(window.getMetaInfo());
      return metaInfo;
    };

//点击提交按钮
const submit = async () => {
  if (!recordDto.value.id) {
    requesttt.value.certName = recordDto.value.name
    requesttt.value.certNo = recordDto.value.idNumber
    requesttt.value.metaInfo = await getMetaInfo()
    startRealPersonAuth() 
    

    // } else {
    //   const { code, message, data } = await UpdateSysUser(sysUser.value)
    //   if (code === 200) {
    //     dialogVisible.value = false
    //     ElMessage.success('操作成功')
    //     fetchData()
    //   } else {
    //     ElMessage.error(message)
    //   }
  }
}

const ceshi = () => {
  console.log(recordDto.value.sex)
}
</script>

<style>
</style>